package com.seeyon.apps.kkSample.utils;

import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.GlobalNames;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.flag.BrowserEnum;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;

public class UserSessionUtil {

    private static OrgManager orgManager;

    /**
     * 虚拟创建seesion
     *
     * @param member 人员ID或者登录名
     * @throws BusinessException
     */
    public static void newUserSession(String member) throws BusinessException {
        if (AppContext.getCurrentUser() == null) {
            V3xOrgMember HandleMember;
            try {
                Long memberId = Long.valueOf(member);
                HandleMember = getOrgManager().getMemberById(memberId);
            } catch (Exception e) {
                HandleMember = getOrgManager().getMemberByLoginName(member);
            }
            User user = new User();
            user.setId(HandleMember.getId());
            user.setAccountId(HandleMember.getOrgAccountId());
            user.setDepartmentId(HandleMember.getOrgDepartmentId());
            user.setLoginAccount(HandleMember.getOrgAccountId());
            user.setLoginName(HandleMember.getLoginName());
            user.setName(HandleMember.getName());
            user.setBrowser(BrowserEnum.IE);
            AppContext.putThreadContext(GlobalNames.SESSION_CONTEXT_USERINFO_KEY, user);
        }
    }

    /**
     * 注销seesion
     *
     * @throws BusinessException
     */
    public static void clearUserSession() throws BusinessException {
        AppContext.removeThreadContext("SESSION_CONTEXT_USERINFO_KEY");
    }

    private static OrgManager getOrgManager() {
        if (orgManager == null) {
            orgManager = (OrgManager) AppContext.getBean("orgManager");
        }
        return orgManager;
    }

}
